package com.have.blog.web.controller;

import com.have.blog.base.wrapper.CommonPage;
import com.have.blog.base.wrapper.Wrapper;
import com.have.blog.web.entity.document.BlogDocument;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


@RequestMapping("/search")
@RestController
@Slf4j
public class SearchController {
    @Autowired
    private ElasticsearchRestTemplate esRestTemplate;

    @RequestMapping("/searchBlog")
    public Wrapper<CommonPage<BlogDocument>> searchBlog(@RequestParam(name = "keyword") String keyword,
                              @RequestParam(name = "pageNum") Integer pageNum,
                              @RequestParam(name = "pageSize") Integer pageSize) {
        Criteria criteria = new Criteria("title")
                .contains(keyword)
                .or("summary")
                .contains(keyword);
        CriteriaQuery query = new CriteriaQuery(criteria);
        query.setPageable(PageRequest.of(pageNum, pageSize));
        log.info("search: {}", query.toString());
        SearchHits<BlogDocument> result = esRestTemplate.search(query, BlogDocument.class);
        Iterator<SearchHit<BlogDocument>> iterator = result.iterator();
        List<BlogDocument> blogList= new ArrayList<>();
        while (iterator.hasNext()) {
            SearchHit<BlogDocument> next = iterator.next();
            BlogDocument content = next.getContent();
            blogList.add(content);
        }
        int pageNumber = query.getPageable().getPageNumber();
        long totalHits = result.getTotalHits();
        CommonPage<BlogDocument> page = CommonPage.restPage(blogList);
        page.setPageNum(pageNumber);
        page.setTotal(totalHits);
        return Wrapper.success(page);
    }
}
